#include<stdlib.h>
//#include<stdio.h>
//#include<stdint.h>
#include<string.h>
#include "mifare.h"
#include "include/ca51f003_config.h"	
#include "include/uart.h"
#include "des.h"
/////////////////////////////////////////////////////////////////////
//功    能：发送RATS请求
//参数说明: buf 获取返回值 length返回值长度
//返    回: 无
/////////////////////////////////////////////////////////////////////
int8_t DESFire_RATS(uint8_t *buf,uint8_t *length)
{
	unsigned char crc_lsb = 0;
  unsigned char crc_msb = 0;
  int8_t status = MI_EMPTY;
  transceive_buffer  mf_com_data;
  transceive_buffer  *pi;
  pi = &mf_com_data;
	spi_write_reg(fifolevel_reg, 0x80);                    //clear fifo data
  spi_write_reg(recstate_reg, 0x7F);
	mf_com_data.mf_command =PCD_TRANSCEIVE;
	mf_com_data.mf_length  = 4;
	mf_com_data.mf_data[0] = 0xE0;
	mf_com_data.mf_data[1] = 0x50|PICC_CID;
	pcd_get_crc(CRC_A, 2, mf_com_data.mf_data, &crc_lsb, &crc_msb);
	mf_com_data.mf_data[2] = crc_lsb;
	mf_com_data.mf_data[3] = crc_msb;
	spi_write_reg(snd_byte_num_reg, mf_com_data.mf_length);
	spi_write_reg(snd_bit_num_reg, 0x00);
	status = pcd_com_transceive(pi);
	if(status == MI_OK)
	{
		memcpy(buf,mf_com_data.mf_data,8);
		length[0] = 8;
//		for(i=0;i<8;i++)
//		{
//			uart_printf(" %02x ",(int)mf_com_data.mf_data[i]);
//		}
//		uart_printf("RAST OK\r\n");
	}
	return status;
}

/////////////////////////////////////////////////////////////////////
//功    能：发送HALT请求
//参数说明: 无
//返    回: 无
/////////////////////////////////////////////////////////////////////
int8_t DESFire_HALT()
{
	unsigned char crc_lsb = 0;
  unsigned char crc_msb = 0;
  int8_t status = MI_EMPTY;
  transceive_buffer  mf_com_data;
  transceive_buffer  *pi;
  pi = &mf_com_data;
	spi_write_reg(fifolevel_reg, 0x80);                    //clear fifo data
  spi_write_reg(recstate_reg, 0x7F);
	mf_com_data.mf_command =PCD_TRANSCEIVE;
	mf_com_data.mf_length  = 4;
	mf_com_data.mf_data[0] = 0xCA;
	mf_com_data.mf_data[1] = PICC_CID;
	pcd_get_crc(CRC_A, 2, mf_com_data.mf_data, &crc_lsb, &crc_msb);
	mf_com_data.mf_data[2] = crc_lsb;
	mf_com_data.mf_data[3] = crc_msb;
	spi_write_reg(snd_byte_num_reg, mf_com_data.mf_length);
	spi_write_reg(snd_bit_num_reg, 0x00);
	status = pcd_com_transceive(pi);
	return status;
}
